/*
 *@author:陈旭光，Chen XuG,chenxvguang1991@163.com
 */

var can0=document.getElementById('game0');
var ctx0=can0.getContext('2d');
var can1=document.getElementById('game1');
var ctx1=can1.getContext('2d');
var playBtn=document.getElementById('playBtn');
var replayBtn=document.getElementById('replayBtn');
var gameArea=document.getElementById('gameArea');
var lastTime,deltaTime;//每帧时间间隔
var gameRun=true,birdUp=false,gameOver=false,readyPlay=false;//游戏状态参数
var bagChange=0,birdChange=0;//改变背景，bird,pillae颜色参数
var bird,pillar,collsion,data,sound;
window.onload=game;
function game() {
        bird=new Bird();
        pillar=new Pillar();
        data=new Data();
        sound=new Sound();
        collision=new Collision();
        init();
}

        document.addEventListener('touchstart',up,false);
        playBtn.addEventListener('touchend',ready,false);
        replayBtn.addEventListener('touchend',replay,false);

function init(){
        pillar.init();
}

function loop(){
        if(!gameOver){window.requestAnimFrame(loop);}
        deltaTime=Date.now()-lastTime;
        lastTime=Date.now();
       if(deltaTime>15){ ctx0.clearRect(0,0,288,512);
               ctx1.clearRect(0,0,288,512);
               pillar.move();
               pillar.draw();
               bird.draw();
               collision.draw();
               data.draw();}
}
function ready(){
        readyPlay=true;
        this.parentNode.style.display='none';
        lastTime=Date.now();
        loop();

}
function replay(){
        bagChange++;
        birdChange++;
        if(bagChange%2==1){gameArea.style.background='url(img/bg_night.png) repeat-x'}
          else{gameArea.style.background='url(img/bg_day.png) repeat-x'}
        gameRun=true,birdUp=false,gameOver=false,readyPlay=true;
        game();
        lastTime=Date.now();
        loop();
        replayBtn.parentNode.style.display='none';
}
function up(e){
        e=e||window.event;
        e.preventDefault();
       if(gameRun&&readyPlay){birdUp=true;sound.up.play()};

}

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
    function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
      return window.setTimeout(callback, 1000 / 60);
    };
})();

function calLength2(x1, y1, x2, y2) {
  return Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2);
}
//------------------bird-------------------
function Bird(){
        this.x=70;
        this.y=300;
        this.w=48;
        this.t=0;//下落时间
        this.g=20;//下落加速度
        this.deltaY=0;//下落距离
        this.upY=0;//上升前位置
        this.img1=[];
        this.img2=[];
        for(var i=0;i<3;i++){
             this.img1[i]=new Image();
             this.img2[i]=new Image();
             this.img1[i].src='img/bird1_'+i+'.png'
             this.img2[i].src='img/bird2_'+i+'.png'
        }
        this.index=0;//img[this.index]
        this.deltaT=0;//图片改变时间间隔
        this.deg=0;//图片旋转角度
       
}

Bird.prototype={
        draw:function(){
                if(birdUp){//bird上升事件
                            this.t=0;
                            this.y-=deltaTime*1.2;
                            this.deg= this.y-this.upY;
                            if( this.upY-this.y>=60){
                                 birdUp=false;this.upY=0
                            }
                        }
                        else
                        {   
                            this.t+=deltaTime/1000;
                            var dis=this.g*this.t*this.t/2;  //s=i/2*a*t*t
                            this.deltaY+=dis  ;     
                            this.deg+= dis;
                             this.y+=dis;
                            if(this.deg>=90){
                                this.deg=90;
                            }
                            
                            if(this.y>=360) {this.y=360;gameOver=true ;sound.die.play()}//bird位置大于360，bird死亡，游戏结束
                            this.upY=this.y;
                }
                collision.birdX=this.x+24;
                collision.birdY=this.y+24;
                var i=birdChange%2;
                if(i==1){
                ctx1.save();
                ctx1.translate(this.x+24,this.y+24);
                ctx1.rotate(this.deg*Math.PI/180);
                ctx1.translate(-24,-24);
                ctx1.drawImage(this.img1[this.index%3],0,0,this.w,this.w);
                ctx1.restore();
                this.deltaT+=deltaTime;
                if(this.deltaT>=150){this.index++;this.deltaT=0;}
                }
                else if(i==0)
                {
                ctx1.save();
                ctx1.translate(this.x+24,this.y+24);
                ctx1.rotate(this.deg*Math.PI/180);
                ctx1.translate(-24,-24);
                ctx1.drawImage(this.img2[this.index%3],0,0,this.w,this.w);
                ctx1.restore();
                this.deltaT+=deltaTime;
                if(this.deltaT>=150){this.index++;this.deltaT=0;}
                }
                
        }
}
//------------------pillar------------------
function Pillar(){
    this.num=10;
    this.x=[];
    this.y=[];
    this.alive=[];
    this.index=0;
    this.imgUp=[];
    this.imgDown=[];
}
Pillar.prototype={
    init:function(){
            for(var i=0;i<this.num;i++){
                  this.x[i]=0;
                  this.y[i]=0;
                  this.alive[i]=false;
                  this.imgUp[i]=new Image();
                  this.imgDown[i]=new Image();
                  this.imgUp[i].src='img/pipe_up.png';
                  this.imgDown[i].src='img/pipe_down.png';
            } 
            this.alive[0]=true;
            this.x[0]=288;
            this.y[0]=Math.floor(Math.random()*150+50);
           

    },
    draw:function(){
          for(var i=0;i<this.num;i++){
                
                if(this.alive[i]){
                      ctx0.save();
                      ctx0.drawImage(this.imgDown[i],this.x[i],this.y[i]-this.imgDown[i].height,this.imgDown[i].width,this.imgDown[i].height);
                      ctx0.restore();
                      ctx0.save();
                      ctx0.drawImage(this.imgUp[i],this.x[i],this.y[i]+100,this.imgUp[i].width,this.imgUp[i].height);
                      ctx0.restore();
                     }
                }
          },
      move:function(){
              this.born();
              for(var i=0;i<this.num;i++){
                      if(this.alive[i]){
                            this.x[i]-=2;//pillar 速度
                            if(this.x[i]<=-50) this.alive[i]=false; //位置小于-50,pillar状态改变
                            if(this.x[i]==20&&gameRun) {data.score++;sound.score.play()}//判断得分
                            if(this.x[i]>=20&&this.x[i]<=170){//为碰撞类参数赋值
                                   collision.pillarX=this.x[i];
                                   collision.pillarY=this.y[i];
                            }
                           
                      }
                  }
              },
      born:function(){
              if(this.x[this.index%10]<=90){
                          this.alive[(this.index+1)%10]=true;
                          this.x[(this.index+1)%10]=288;
                          this.y[(this.index+1)%10]=Math.floor(Math.random()*150+50);
                          this.index++;
              }
        }
}
//------------------collision--------------
function Collision(){
           this.birdX=0;
           this.birdY=0;
           this.pillarX=0;
           this.pillarY=0;
           this.img=new Image();
           this.img.src='./img/gameover.png';
           this.r=12;//碰撞距离
 }                        

Collision.prototype={
   draw:function(){
            //碰撞检测
          if(gameRun){if(this.pillarX>=20&&this.pillarX<40){
                              
                              if (     (calLength2(this.birdX,this.birdY,this.pillarX+52,this.pillarY)<=this.r*this.r)    ||
                                    (calLength2(this.birdX,this.birdY,this.pillarX+52+100,this.pillarY)<=this.r*this.r)   )
                                     {gameRun=false;sound.hit.play();}
                                       
                            
                    }
                    else if(  this.pillarX>=40&&this.pillarX<90){
                             if(  (this.birdY<=this.pillarY+this.r)||
                                   (this.birdY>=(this.pillarY-this.r+100))  )  
                                  {gameRun=false;sound.hit.play();}
                                 
                           
                    }
                    else if(  this.pillarX>=90&&this.pillarX<110){
                              if (  (calLength2(this.birdX,this.birdY,this.pillarX,this.pillarY)<=this.r*this.r)||
                                (calLength2(this.birdX,this.birdY,this.pillarX,this.pillarY+100)<=this.r*this.r)||
                                (this.birdY>=(this.pillarY+this.r+100))||
                                (this.birdY<=(this.pillarY-this.r))  )
                                { gameRun=false;sound.hit.play();}
                                   
                             
                    }}
          
        if(!gameRun||gameOver){
                ctx1.save();
                ctx1.drawImage(collision.img,42,150,204,54);
                ctx1.restore(); 
                replayBtn.parentNode.style.display='block';
          };

          }
   }


//------------------data-------------------
function Data(){
        this.score=0;
        this.img0=new Image();
        this.img1=new Image();
        this.img3=new Image();
        this.img3.src='./img/title.png';
}


Data.prototype={
  draw:function(){
    if(this.score<10){
      this.img0.src='./img/'+this.score+'.png';
      ctx1.save();
          ctx1.drawImage(this.img0,130,50,24,44);
          ctx1.restore();
    }
    else if(this.score>=10&&this.score<100){
      var x0=this.score%10;
      var x1=Math.floor(this.score/10);
      this.img0.src='./img/'+x0+'.png';
      this.img1.src='./img/'+x1+'.png';
      ctx1.save();
          ctx1.drawImage(this.img1,119,50,24,44);
          ctx1.drawImage(this.img0,134,50,24,44);
          ctx1.restore();
    }
    else{
      this.img0.src='./img/6.png';
      ctx1.save();
          ctx1.drawImage(this.img0,106,50,24,44); 
          ctx1.drawImage(this.img0,131,50,24,44);        
          ctx1.drawImage(this.img0,156,50,24,44);
          ctx1.restore();
    }
        
        ctx1.save();
        ctx1.drawImage(this.img3,2,2,120,64);
        ctx1.restore();
  }
}

//------------------sound-----------------

function Sound(){
       this.up=new Audio();
       this.up.src='./sound/wing.mp3';
       this.up.loop=false;
       this.hit=new Audio();
       this.hit.src='./sound/hit.mp3';
       this.hit.loop=false;
       this.score=new Audio();
       this.score.src='./sound/point.mp3';
       this.score.loop=false;
       this.die=new Audio();
       this.die.src='./sound/die.mp3';
       this.die.loop=false;

}